package me.caofeng.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.util
 * @Description: json处理工具
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-20 10:34
 * @Version: V1.0
 */
public class JsonUtil {
    private static ObjectMapper objectMapper;
    private static Logger LOGGER = LogManager.getLogger(JsonUtil.class);

    /**
     * @Author:曹峰 blog.caofeng.me
     * @Date: 2017/6/20 10:36
     * @Description: 将对象转为json字符串
     */
    public static String toJSon(Object object) {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }

        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static <T> T listFromJson(String jsonStr) {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }

        TypeReference<T> typeReference = new TypeReference<T>() {
            @Override
            public Type getType() {
                return super.getType();
            }
        };

        try {
            return objectMapper.readValue(jsonStr, typeReference);
        } catch (Exception e) {
            LOGGER.error(e);
        }

        return null;
    }

    public static <T> T fromJson(String jsonStr, Class<T> valueType) {
        if (null == objectMapper) {
            objectMapper = new ObjectMapper();
        }

        try {
            return objectMapper.readValue(jsonStr, valueType);
        } catch (IOException e) {
            LOGGER.error(e);
        }

        return null;
    }


    public static void main(String[] args){
        String a = "fsd";
        String json = toJSon(a);
        LOGGER.debug(json);
        String b = fromJson(json,String.class);
    }

}
